import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
  MaterialChargeServiceProxy,
  MaterialChargeLogDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';

import { Table } from 'primeng/table';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';

@Component({
  selector: 'logMaterialModal',
  templateUrl: './log-material-modal.component.html'
})
export class LogMaterialModalComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('logDataTable') logDataTable: Table;
  @ViewChild('logPaginator') logPaginator: Paginator;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;

  id = '';

  advancedFiltersAreShown = false;
  filterText = '';
  tab = 1;

  primengTableLogHelper: PrimengTableHelper;

  logs = new Array<MaterialChargeLogDto>();

  constructor(
    injector: Injector,
    private _materialService: MaterialChargeServiceProxy
  ) {
    super(injector);
    this.primengTableLogHelper = new PrimengTableHelper();
  }

  show(id: string): void {
    this.id = id;

    this.active = true;

    this.modal.show();

    this.getLogs();
  }

  getLogs(event?: LazyLoadEvent) {
    if (!this.id) {
      return;
    }

    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.logPaginator.changePage(0);
      return;
    }

    this.primengTableLogHelper.showLoadingIndicator();

    this._materialService
      .getSomeOneMaterialLogs(
        this.id,
        this.filterText,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        this.tab,
        this.primengTableHelper.getSorting(this.logDataTable),
        this.primengTableHelper.getMaxResultCount(this.logPaginator, event),
        this.primengTableHelper.getSkipCount(this.logPaginator, event)
      )
      .subscribe(result => {
        this.primengTableLogHelper.totalRecordsCount = result.totalCount;
        this.primengTableLogHelper.records = result.items;
        this.primengTableLogHelper.hideLoadingIndicator();
      });
  }

  reloadPage(): void {
    this.logPaginator.changePage(this.logPaginator.getPage());
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }

  tabChange(tab: number) {
    this.tab = tab;
    this.reloadPage();
  }
}
